/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-09 09:00:39
 * @LastEditTime: 2023-08-01 00:16:55
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import { ViewIcon, ViewOffIcon } from '@chakra-ui/icons';
import {
  Box,
  Button,
  Checkbox,
  Flex,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Heading,
  Input,
  InputGroup,
  InputRightElement,
  Link,
  Stack,
  Text,
  useColorModeValue,
} from '@chakra-ui/react';

import { Field, FieldProps, Formik } from 'formik';
import { parse, stringify } from 'qs';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Link as ReactRouterLink,
  useLocation,
  useNavigate,
} from 'react-router-dom';

import { LoginInfo } from '@/api/user.service';

import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { loginAction } from '@/store/user';
// import useSocket from '@/socketio/useSocket';

export default function Login() {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { loading, isLogin } = useAppSelector((state) => state.user);
  const { search } = useLocation();
  const navigate = useNavigate();
  const queryObj = search ? parse(search.slice(1)) : {};
  const { redirect = '/', ...otherQuery } = queryObj;
  const queryString = stringify(otherQuery);
  const [show, setShow] = useState(false);
  const handleLogin = async (values: LoginInfo) => {
    try {
      await dispatch(loginAction(values));
    } catch (e) {
      console.log(e);
    }
  };
  // useSocket();
  useEffect(() => {
    if (isLogin) {
      navigate(
        queryString
          ? (`${redirect}?${queryString}` as string)
          : (redirect as string)
      );
    }
  }, [isLogin, navigate, queryString, redirect]);

  return (
    <Flex align="center" justify="center">
      <Stack
        spacing={8}
        mx="auto"
        maxW="lg"
        minW={{ md: 'md' }}
        py={12}
        px={6}
      >
        <Stack align="center">
          <Heading fontSize="4xl">{t('auth.loginAccount')}</Heading>
          {/* <Text fontSize={'lg'} color={'gray.600'}>
            to enjoy all of our cool features ✌️
          </Text> */}
        </Stack>
        <Box
          rounded="lg"
          bg={useColorModeValue('white', 'base.800')}
          boxShadow="lg"
          p={8}
        >
          <Formik
            initialValues={{
              username: '',
              password: '',
              rememberMe: false,
            }}
            onSubmit={(values) => {
              handleLogin(values);
            }}
          >
            {({ handleSubmit, errors, touched }) => (
              <form onSubmit={handleSubmit}>
                <Stack spacing={4}>
                  <Field
                    name="username"
                    validate={(value: string) => {
                      let error;
                      if (!value) {
                        error = t('auth.usernameRequired');
                      }
                      return error;
                    }}
                  >
                    {({ field }: FieldProps) => (
                      <FormControl
                        isRequired
                        isInvalid={Boolean(errors.username && touched.username)}
                      >
                        <FormLabel fontWeight="600" htmlFor="username">
                          {t('profile.username')}
                        </FormLabel>
                        <Input
                          id="username"
                          type="text"
                          variant="filled"
                          {...field}
                          placeholder={t('auth.usernamePlaceholder')}
                        />
                        <FormErrorMessage>
                          {errors.username as string}
                        </FormErrorMessage>
                      </FormControl>
                    )}
                  </Field>
                  {/* <FormControl isRequired>
                    <FormLabel htmlFor="username">username</FormLabel>
                    <Field
                      as={Input}
                      id="username"
                      name="username"
                      type="text"
                      variant="filled"
                    />
                  </FormControl> */}
                  <Field
                    name="password"
                    validate={(value: string) => {
                      let error;
                      if (value.length < 6) {
                        error = t('auth.passwordError');
                      }
                      return error;
                    }}
                  >
                    {({ field }: FieldProps) => (
                      <FormControl
                        isRequired
                        isInvalid={Boolean(errors.password && touched.password)}
                      >
                        <FormLabel fontWeight="600" htmlFor="password">
                          {t('profile.password')}
                        </FormLabel>

                        <InputGroup>
                          <Input
                            id="password"
                            type={show ? 'text' : 'password'}
                            variant="filled"
                            {...field}
                            placeholder={t('auth.passwordPlaceholder')}
                          />
                          <InputRightElement
                            cursor="pointer"
                            onClick={() => setShow(!show)}
                          >
                            {!show ? <ViewOffIcon /> : <ViewIcon />}
                          </InputRightElement>
                        </InputGroup>
                        <FormErrorMessage>
                          {errors.password as string}
                        </FormErrorMessage>
                      </FormControl>
                    )}
                  </Field>

                  <Stack spacing={10}>
                    <Stack
                      direction={{ base: 'row' }}
                      align="start"
                      justify="space-between"
                    >
                      <Field as={Checkbox} id="rememberMe" name="rememberMe">
                        {t('auth.keepLogin')}
                      </Field>
                      <Link
                        as={ReactRouterLink}
                        to="/forgotPassword"
                        color="blue.400"
                      >
                        {t('auth.forgetPass')}?
                      </Link>
                    </Stack>
                    <Button isLoading={loading} bg="base.700" type="submit">
                      {t('auth.signin')}
                    </Button>
                  </Stack>
                </Stack>
              </form>
            )}
          </Formik>
          <Stack pt={6}>
            <Text align="center">
              {t('auth.notHaveAccount')}?{' '}
              <Link as={ReactRouterLink} to="/registry" color="blue.400">
                {t('auth.signup')}
              </Link>
            </Text>
          </Stack>
        </Box>
      </Stack>
    </Flex>
  );
}
